<?php

namespace App\Http\Middleware;

use App\Models\AdminMenuModel;
use Illuminate\Support\Facades\Auth;
use Closure;

class Permission
{
    public function handle($request, Closure $next, $permission)
    {
        $user = Auth::user();
        $permissions = explode('|', $permission);
        $userMenu = array_column($user->getDirectPermissions()->toArray() ?? [], 'name');
        $res = false;

        if(!$user->status){
            $user->token()->delete();
            return response()->error(400, '账户被禁用或已过期');
        }

        foreach ($userMenu as $menuKey) {
            if (in_array($menuKey, $permissions)) {
                $res = true;
            }
        }
        if (!$res) {
            return response()->error(400, '用户无权限');
        }

        return $next($request);
    }
}
